package com.johnzer.frame.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.widget.EditText;

import com.johnzer.frame.app.BaseApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

/**
 * App相关类; 获取版本号 和 app名字
 *
 * @author
 */
public class AppUtils {
    private AppUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");

    }

    /**
     * 在主线程执行runnable
     */
    public static boolean post(Runnable runnable) {
        return BaseApp.getMainThreadHandler().post(runnable);
    }

    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs
                .getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class
                    .forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass,
                    "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // Log.w(TAG, e);
        }

        return hasNavigationBar;

    }

    // 获取NavigationBar的高度：
    public static int getNavigationBarHeight(Context context) {
        int navigationBarHeight = 0;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0 && checkDeviceHasNavigationBar(context)) {
            navigationBarHeight = rs.getDimensionPixelSize(id);
        }
        return navigationBarHeight;
    }

    /**
     * 获取音视频的时长
     *
     * @param path
     * @return
     */
    public static int getMediaDurationSec(String path) {
//		return getMediaDuration1(path);
        return getMediaDuration2(path) / 1000;
    }

    private static int getMediaDuration2(String path) {
        int time = 0;
        try {
            MediaPlayer player = MediaPlayer.create(BaseApp.instance(), Uri.fromFile(new File(path)));
            time = player.getDuration();
            player.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    private static int getMediaDuration1(String path) {
        String duration = null;
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();

        try {
            if (path != null) {
                HashMap<String, String> headers = null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(path, headers);
            }

            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            LogUtils.d("ryan, duration " + duration);
            return Integer.valueOf(duration);
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0;
        } finally {
            mmr.release();
        }
    }

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 获取当前网络类型
     *
     * @return 无线网络返回wifi 手机网络返回mobile 没有网络返回null
     */
    public static String getNetworkType(Context context) {
        String netType = "null";
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = "mobile";
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = "wifi";
        }
        return netType;
    }


    /**
     * @param context
     * @return
     * @author Michaeltang
     * @date 2014-4-28 上午11:54:51
     * @description TODO 判断网络是否连接
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = cm.getActiveNetworkInfo();
        if (null != network && network.isConnected()) {
            if (network.isAvailable()) {
                return true;
            } else {
                ToastUtil.showToastSafe("当前网络不可用");
                return false;
            }
        } else {
            ToastUtil.showToastSafe("您的网络有问题,请检查网络连接");
            return false;
        }
    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本号] 版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获 取 渠道码
     *
     * @param context
     * @return
     */
    public static String getChannelCode(Context context) {
        String code = getMetaData(context, "UMENG_CHANNEL");
        if (code != null) {
            return code;
        }
        return "wenxiaoyou";
    }

    /**
     * 获取产品ID
     *
     * @param context
     * @return
     */
    public static int getProductID(Context context) {
        String id = getMetaData(context, "PRODUCT_ID");
        if (id != null) {
            return Integer.valueOf(id);
        }
        // 返回默认ID
        return 1;
    }

    /**
     * 获 取包内Meta内容
     *
     * @param context
     * @return
     */
    private static String getMetaData(Context context, String key) {
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            Object value = ai.metaData.get(key);
            if (value != null) {
                return value.toString();
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 获 取 Android唯一识别码
     *
     * @return
     */
    public static String getDeviceToken() {
        try {
            String imei = getIMEI(BaseApp.instance());
            String wifimac = getWlanMAC(BaseApp.instance());
            String cpu = getCpuInfo();
            String btMac = getBlueMAC();
            String screenSize = UIUtils.getScreenWidth() + "x"
                    + UIUtils.getScreenHeight();
            LogUtils.d("btMac = " + btMac + "\n screenSize = " + screenSize);
            return MD5Filter.md5String(imei + wifimac + cpu + btMac + screenSize);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获 取 应用程序ID
     *
     * @param context
     * @return
     */
    public static String getAndroidAppID(Context context) {
        String m_szAndroidID = Secure.getString(context.getContentResolver(),
                Secure.ANDROID_ID);
        return m_szAndroidID;
    }

    /**
     * 获 取 wifi mac
     *
     * @param context
     * @return
     */
    public static String getWlanMAC(Context context) {
        WifiManager wm = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
        return m_szWLANMAC;
    }

    /**
     * 获 取 bluetooth mac
     *
     * @return
     */
    public static String getBlueMAC() {
        BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter
        m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String m_szBTMAC = m_BluetoothAdapter.getAddress();
        return m_szBTMAC;
    }

    /**
     * 获 取 手机内存信息
     *
     * @param context
     * @return
     */
    public static String getPhoneMemery(Context context) {
        /** 获取当前手机的内存信息大小 */
        MemoryInfo outInfo = new MemoryInfo();
        return Formatter.formatFileSize(context, outInfo.availMem);
    }

    /**
     * 获取手机厂商 vendor
     */
    public static String getPhoneVendor() {
        return android.os.Build.MANUFACTURER;
    }

    /**
     * 获取手机系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获 取 手机IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager telephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyMgr.getDeviceId();
    }

    public static String getSimCode(Context context) {
        TelephonyManager telephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyMgr.getSubscriberId();
    }

    /**
     * 获 取 手机内存信息 rom_info
     *
     * @return
     */
    public static String getRomInfo() {
        return android.os.Build.MANUFACTURER + "|" + android.os.Build.MODEL
                + "|" + android.os.Build.VERSION.RELEASE + " "
                + android.os.Build.ID;
    }

    public static String getCpuInfo() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("Hardware")) {
                    br.close();
                    fr.close();
                    return line.substring(line.indexOf(':') + 1);
                }

            }
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return android.os.Build.HARDWARE;
    }

    public static String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    // 获取CPU最小频率（单位KHZ）
    public static String getMinCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    // 实时获取CPU当前频率（单位KHZ）
    public static String getCurCpuFreq() {
        String result = "N/A";
        try {
            FileReader fr = new FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            result = text.trim();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 获取CPU名字
    public static String getCpuName() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);
            for (int i = 0; i < array.length; i++) {
            }
            return array[1];
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCPUSerial() {
        String str = "", strCPU = "", cpuAddress = "0000000000000000";
        try {
            // 读取CPU信息
            Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            // 查找CPU序列号
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    // 查找到序列号所在行
                    if (str.indexOf("Serial") > -1) {
                        // 提取序列号
                        strCPU = str.substring(str.indexOf(":") + 1,
                                str.length());
                        // 去空格
                        cpuAddress = strCPU.trim();
                        break;
                    }
                } else {
                    // 文件结尾
                    break;
                }
            }
        } catch (Exception ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return cpuAddress;
    }

    public static String getLastLocation(Context context) {
        String locationProvider;
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        // 获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            // 如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            // 如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            return null;
        }

        // 获取Location
        if (ActivityCompat.checkSelfPermission(BaseApp.instance(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(BaseApp.instance(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Location location = locationManager
                    .getLastKnownLocation(locationProvider);
            if (location != null) {
                return location.getLatitude() + "," + location.getLongitude();
            }
        }
        return null;
    }

    /*public static void getAMPLocation() {
        final AMapLocationClient locationClient = new AMapLocationClient(
                BaseApplication.getCurruntContext());
        AMapLocationClientOption locationOption = new AMapLocationClientOption();
        // 设置定位模式为低功耗模式
        locationOption.setLocationMode(AMapLocationMode.Battery_Saving);
        // 设置为单次定位
        locationOption.setOnceLocation(true);
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
        // 设置定位监听
        locationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation location) {
                if (location.getErrorCode() == 0) {
                    // 成功
                    if (!location.getProvider().equalsIgnoreCase(
                            LocationManager.GPS_PROVIDER)) {
                        String addr = location.getCountry()
                                + location.getProvince() + location.getCity()
                                + location.getDistrict()
                                + location.getAddress();
                        AppUtils.setSPString(
                                BaseApplication.getCurruntContext(),
                                "location", addr);
                        LogUtils.d("定位成功：" + addr);
                        // sb.append("城市编码 : " + location.getCityCode() + "\n");
                        // sb.append("区域 码   : " + location.getAdCode() + "\n");
                        // sb.append("兴趣点    : " + location.getPoiName() +
                        // "\n");
                    }
                } else {
                    // 失败
                    LogUtils.d("定位失败");
                }
                // 停止定位
                locationClient.stopLocation();
                locationClient.onDestroy();
            }
        });
    }
*/
    public static String getPhoneIpAddress() {
        String nType = getNetworkType(BaseApp.instance());
        if ("mobile".equals(nType)) {
            return getLocalIpAddress();
        } else if ("wifi".equals(nType)) {
            return getWifiIpAddr();
        }
        return null;
    }

    /**
     * 获取WiFi环境下的ip地址
     *
     * @return
     */
    public static String getWifiIpAddr() {
        WifiManager wifiManager = (WifiManager) BaseApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
    }

    /**
     * 获取移动数据下的IP地址
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && /* !inetAddress.isLinkLocalAddress() */inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
//			LogUtils.e("WifiPreference IpAddress", ex.t);
        }
        return null;
    }

  /*  *//**
     * 获取当前国家代码
     *
     * @param ctx
     * @return
     *//*
    public static String GetCountryZipCode(Context ctx) {
        String CountryID = "";
        String CountryZipCode = "";
        TelephonyManager manager = (TelephonyManager) ctx
                .getSystemService(Context.TELEPHONY_SERVICE);
        // getNetworkCountryIso
        CountryID = manager.getSimCountryIso().toUpperCase();
        String[] rl = ctx.getResources().getStringArray(R.array.CountryCodes);
        for (int i = 0; i < rl.length; i++) {
            String[] g = rl[i].split(",");
            if (g[1].trim().equals(CountryID.trim())) {
                CountryZipCode = g[0];
                break;
            }
        }

        return CountryZipCode;
    }*/

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    public static boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }
        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
}
